using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Markup;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.Utility;

namespace Common.Unity.Configuration
{
	[ContentProperty( "InjectionMembers" )]
	public class UnityType : IContainerConfigurationCommand
	{
		public string BuildName { get; set; }

		public Type Type { get; set; }

		public Type MapTo { get; set; }

		public LifetimeManager Lifetime { get; set; }

		public ObservableCollection<InjectionMember> InjectionMembers
		{
			get { return injectionMembers ?? ( injectionMembers = new ObservableCollection<InjectionMember>() ); }
		}	ObservableCollection<InjectionMember> injectionMembers;

		public ObservableCollection<UnityContainerTypeConfiguration> TypeConfigurations
		{
			get { return typeConfigurations ?? ( typeConfigurations = new ObservableCollection<UnityContainerTypeConfiguration>() ); }
		}	ObservableCollection<UnityContainerTypeConfiguration> typeConfigurations;
        
		public void Configure( IUnityContainer container )
		{
			Guard.ArgumentNotNull(container, "container");

			var type = MapTo ?? Type;
			var members = ( from member in InjectionMembers select member.Create( container, type ) ).ToArray();
			container.RegisterType( Type, type, BuildName, Lifetime, members );

			foreach ( var item in TypeConfigurations )
			{
				item.Configure( container, this );
			}
		}
	}
}